/*
 * Copyright 2012 nekdo.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cz.muni.fi.heathtow.rest;


import com.google.gson.Gson;
import com.sun.jersey.spi.inject.Inject;
import cz.muni.fi.heathrowapi.StewardService;
import cz.muni.fi.heathrowapi.dto.StewardDTO;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import org.springframework.context.annotation.Scope;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 *
 * @author Jan Richter
 */
@Component
@Path("/stewards")
@Scope("request")
public class StewardResourceImpl implements StewardResource {

    @Inject
    private StewardService stewardService;
    @Context
    UriInfo info;
    
    @Override
    @GET
    @Produces("application/json")
    public String getStewards() {
        try{            
            authenticate(RestAuthentication.REST_USERNAME, RestAuthentication.REST_PASSWORD);
            return new Gson().toJson(stewardService.findAll());
        } catch (Exception ex){
            return ex.getLocalizedMessage();
        } 
    }

    @Override
    @GET
    @Path("/{id}")
    @Produces("application/json")
    public String getSteward(@PathParam("id") String id) {
        try{
            authenticate(RestAuthentication.REST_USERNAME, RestAuthentication.REST_PASSWORD);
            return new Gson().toJson(stewardService.get(Long.parseLong(id)));
        } catch (Exception ex) {
            return ex.getLocalizedMessage();
        }
    }
    
    @Override
    @GET
    @Path("/pid/{id}")
    @Produces("application/json")
    public String getStewardByPersonalId(@PathParam("id") String personalId) {
        try{
            authenticate(RestAuthentication.REST_USERNAME, RestAuthentication.REST_PASSWORD);
            return new Gson().toJson(stewardService.findByPersonalId(Long.parseLong(personalId)));
        } catch (Exception ex) {
            return ex.getLocalizedMessage();
        }
    }

    @Override
    @PUT
    @Produces("text/plain")
    public String updateSteward(@QueryParam("id") String id, @QueryParam("fname") String firstName,
        @QueryParam("lname")String lastName, @QueryParam("persid") String personalId) {
        
        if(StringUtils.hasText(id)) {
            try{
                authenticate(RestAuthentication.REST_USERNAME, RestAuthentication.REST_PASSWORD);
                StewardDTO steward = new StewardDTO();
                steward.setFirstName(firstName);
                steward.setId(Long.parseLong(id));
                steward.setLastName(lastName);
                steward.setPersonalId(Long.parseLong(personalId));

                stewardService.update(steward);
                return "success";
            } catch (Exception ex) {
                return ex.getLocalizedMessage();
            }
        }
        return "no id set";
    }

    @Override
    @POST
    @Produces("text/plain")
    public String createSteward(@QueryParam("fname") String firstName,
        @QueryParam("lname") String lastName, @QueryParam("persid") String personalId) {
        
        try{
            authenticate(RestAuthentication.REST_USERNAME, RestAuthentication.REST_PASSWORD);
            StewardDTO steward = new StewardDTO();
            steward.setFirstName(firstName);
            steward.setLastName(lastName);
            steward.setPersonalId(Long.parseLong(personalId));

            stewardService.create(steward);
            return "success";
        } catch (Exception ex){
            return ex.getLocalizedMessage();
        }
    }

    @Override
    @DELETE
    @Path("/{id}")
    @Produces("text/plain")
    public String deleteSteward(String id) {
        try{
            authenticate(RestAuthentication.REST_USERNAME, RestAuthentication.REST_PASSWORD);
            StewardDTO steward = stewardService.get(Long.parseLong(id));
            if(steward != null)
                stewardService.remove(steward);
            return "success";
        } catch (Exception ex){
            return ex.getLocalizedMessage(); 
        }
    }
 
    private void authenticate(String username, String password) {
        Authentication authentication = new UsernamePasswordAuthenticationToken(username, password);
        SecurityContextHolder.getContext().setAuthentication(authentication);
    }
    
}
